package com.yc.demo.filter;

import java.io.*;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * <p></p>
 *
 * @author: YuanChilde
 * @date: 2020-02-13 15:35
 * @version: 1.0
 * Modification History:
 * Date    Author      Version     Description
 * -----------------------------------------------------------------
 * 2020-02-13 15:35    YuanChilde     1.0        新增
 */
public class HelloFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest hrequest = (HttpServletRequest)servletRequest;
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) servletResponse);
        try {
            if (hrequest.getRequestURI().indexOf("/index") != -1 || hrequest.getRequestURI().indexOf("/asd") != -1 || hrequest.getRequestURI().indexOf("/online") != -1 || hrequest.getRequestURI().indexOf("/login") != -1) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                wrapper.sendRedirect("/login");
            }
        }catch (Exception e) {
            // 发生异常，保存异常栈，路由到错误controller
            servletRequest.setAttribute("error", e);
            servletRequest.getRequestDispatcher("/error").forward(servletRequest, servletResponse);
        }
    }
}
